package com.sunday.haowushop.ui.mine.details;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.haowushop.R;
import com.sunday.haowushop.adapter.CommonAdapter;
import com.sunday.haowushop.adapter.ViewHolder;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.BalanceDetail;
import com.sunday.haowushop.http.ApiClient;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/8/1.
 */

public class BalanceListFragment extends BaseFragment {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.txt_extra)
    TextView txtExtra;

    private Integer type;//类型（1-余额 2-服务费）
    private long memberId;

    private CommonAdapter<BalanceDetail> adapter;
    private List<BalanceDetail> dataSet = new ArrayList<>();

    public static BalanceListFragment newInstance(int type) {
        BalanceListFragment fragment = new BalanceListFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApp.getInstance().getMember().getId();
       txtExtra.setVisibility(type==2?View.VISIBLE:View.GONE);
        handlerRecyclerView();
        getData();
    }

    private int pageNo = 1;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;

    private void handlerRecyclerView() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<BalanceDetail>(mContext, R.layout.item_balance_detail, dataSet) {
            @Override
            public void convert(ViewHolder holder, BalanceDetail balanceDetail) {
                bind(holder, balanceDetail);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });

    }

    private void bind(ViewHolder holder, BalanceDetail balanceDetail) {
        if (type == 1) {
            ((TextView) holder.getView(R.id.title)).setText(balanceDetail.getMoney().compareTo(BigDecimal.ZERO) > 0 ? "零售利润或奖励分红" : "提现");
            ((TextView) holder.getView(R.id.time)).setText(balanceDetail.getCreateTime());
            holder.getView(R.id.number).setVisibility(balanceDetail.getOrderNo() == null ? View.GONE : View.VISIBLE);
            ((TextView) holder.getView(R.id.number)).setText("订单编号：" + balanceDetail.getOrderNo());
            ((TextView) holder.getView(R.id.money)).setText(balanceDetail.getMoney().compareTo(BigDecimal.ZERO) > 0 ?
                    String.format("+%s", balanceDetail.getMoney().setScale(2, RoundingMode.HALF_UP)) : String.format("-%s", balanceDetail.getMoney().setScale(2, RoundingMode.HALF_UP)));

            ((TextView) holder.getView(R.id.money)).setTextColor(balanceDetail.getMoney().compareTo(BigDecimal.ZERO) > 0 ?
                    mContext.getResources().getColor(R.color.colorPrimary) : mContext.getResources().getColor(R.color.material_green));
        } else {
            ((TextView) holder.getView(R.id.title)).setText("培训服务费");
            ((TextView) holder.getView(R.id.time)).setText(balanceDetail.getCreateTime());
            holder.getView(R.id.number).setVisibility(View.GONE);
            ((TextView) holder.getView(R.id.money)).setText(String.format("+%s", balanceDetail.getMoney().setScale(2, RoundingMode.HALF_UP)));
            ((TextView) holder.getView(R.id.money)).setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
        }
    }


    public void refresh() {
        pageNo = 1;
        getData();
    }


    @Override
    public void onResume() {
        super.onResume();
    }


    public void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<BalanceDetail>>> call = ApiClient.getApiAdapter().getBalanceExtraDetail(memberId, type, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<BalanceDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<BalanceDetail>>> call, Response<ResultDO<List<BalanceDetail>>> response) {
                if (isFinish||response.body()==null) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<BalanceDetail>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<BalanceDetail>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }


}

